package open.intellijboy.core.exception;


import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import open.intellijboy.framework.core.exception.BusinessException;
import open.intellijboy.framework.core.exception.SystemException;
import open.intellijboy.framework.core.exception.ValidationException;
import open.intellijboy.framework.core.response.StatusCode;
import open.intellijboy.framework.core.response.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     *
     * @param e 业务异常
     * @return Result
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.warn("业务异常: {}", e.getErrorMessage(), e);
        return Result.failure(e.getErrorCode(), e.getErrorMessage());
    }

    /**
     * 处理系统异常
     *
     * @param e 系统异常
     * @return Result
     */
    @ExceptionHandler(SystemException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleSystemException(SystemException e) {
        log.error("系统异常: {}", e.getErrorMessage(), e);
        return Result.failure(e.getErrorCode(), e.getErrorMessage());
    }

    /**
     * 处理校验异常
     *
     * @param e 校验异常
     * @return Result
     */
    @ExceptionHandler(ValidationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleValidationException(ValidationException e) {
        log.warn("校验异常: {}", e.getErrorMessage(), e);
        return Result.failure(e.getErrorCode(), e.getErrorMessage());
    }

    /**
     * 处理JSR303校验异常 - @RequestBody
     *
     * @param e 方法参数校验异常
     * @return Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult()
                               .getFieldErrors()
                               .stream()
                               .map(FieldError::getDefaultMessage)
                               .collect(Collectors.joining(", "));
        log.warn("参数校验异常: {}", errorMessage);
        return Result.failure(StatusCode.USER_ERROR_0001.getCode(), errorMessage);
    }

    /**
     * 处理JSR303校验异常 - @ModelAttribute
     *
     * @param e 绑定异常
     * @return Result
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBindException(BindException e) {
        String errorMessage = e.getBindingResult()
                               .getFieldErrors()
                               .stream()
                               .map(FieldError::getDefaultMessage)
                               .collect(Collectors.joining(", "));
        log.warn("参数绑定异常: {}", errorMessage);
        return Result.failure(StatusCode.USER_ERROR_0001.getCode(), errorMessage);
    }

    /**
     * 处理JSR303校验异常 - @RequestParam/@PathVariable
     *
     * @param e 约束违反异常
     * @return Result
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
        String errorMessage = e.getConstraintViolations()
                               .stream()
                               .map(ConstraintViolation::getMessage)
                               .collect(Collectors.joining(", "));
        log.warn("约束违反异常: {}", errorMessage);
        return Result.failure(StatusCode.USER_ERROR_0001.getCode(), errorMessage);
    }

    /**
     * 处理其他未知异常
     *
     * @param e 异常
     * @return Result
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e) {
        log.error("未知异常: {}", e.getMessage(), e);
        return Result.failure(StatusCode.USER_ERROR_0001.getCode(), "系统内部错误，请联系管理员");
    }
}

